/**
 * @(#) DomesticBizTripProxy.as
 *
 * @date		2009. 04. 6.
 * @version		1.0
 * @author		Shin, Yunwoo
 * @description	 국경일 및 휴일정보 Proxy - Proxy
 * 				월별 국경일 및 휴일 정보를 가져온다.
 */
package com.skt.common_hr.biztrip_nos.model
{
	import com.skt.common_hr.biztrip_nos.BizTripFacade;
	import com.skt.common_hr.biztrip_nos.model.vo.AdjustBaseVO;
	import com.skt.common_hr.biztrip_nos.model.vo.BizTripMemberVO;
	import com.skt.common_hr.biztrip_nos.model.vo.BizTripPlaceVO;
	import com.skt.common_hr.biztrip_nos.model.vo.BizTripSummaryVO;
	import com.skt.common_hr.biztrip_nos.model.vo.MemberAdjustVO;
	import com.skt.common_hr.biztrip_nos.model.vo.MemberCarfareVO;
	import com.skt.common_hr.biztrip_nos.model.vo.MemberDetailCostVO;
	import com.skt.common_hr.common.puremvc.CommonProxy;
	import com.wcl.dataloader.*;
	import com.wcl.utils.DateUtil;
	import com.wcl.utils.StringUtil;
	
	import mx.collections.ArrayCollection;
	import mx.managers.CursorManager;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	
	public class DomesticBizTripProxy extends CommonProxy
	{
		public static const NAME:String = "DomesticBizTripProxy";
		
		public var summary:BizTripSummaryVO;
		public var places:ArrayCollection;
		public var members:ArrayCollection;
		public var memberAdjusts:ArrayCollection;
		public var memberCarfare:ArrayCollection;
		public var memberDetailCost:ArrayCollection;
		public var adjustBase:ArrayCollection;
		
		public var outKey:String;
		private var saveType:String;
		
		/**
		 * 생성자
		 * 
		 * @param
		 * @return void
		 */
		public function DomesticBizTripProxy(data:Object=null)
		{
			super(NAME, data);
		}
		

		/**
		 * data load를 수행
		 * 		- DataLoader 를 생성하고 Import Parameter 객체를 생성, RFC를 호출
		 * 
		 * @param pernr 사번,대상월
		 * @return void
		 */
		public function load(key1:String, key2:String):void
		{
			var param:Object = new Object();
			param["I_GWAREKEY01"] = key1;
			param["I_GWAREKEY02"] = key2;
			
			loadData("Z_HR_T002", param, resultLoad, faultLoad);
		}
		

		/**
		 * data load를 수행
		 * 		- DataLoader 를 생성하고 Import Parameter 객체를 생성, RFC를 호출
		 * 
		 * @param pernr 사번,대상월
		 * @return void
		 */
		public function save(bApproval:Boolean, bAdjust:Boolean, bModify:Boolean, status:String, key1:String, key2:String, 
							table0:Array, table1:Array, table2:Array, table3:Array=null, table4:Array=null, table5:Array=null,
							html:String=""):void
		{
			var param:Object = new Object();
			param["I_GWAREKEY01"] = key1;
			param["I_GWAREKEY02"] = key2;
			param["I_TRPAYC"]	= (bAdjust)?"X":"";
			param["I_TRCONV"]	= (bModify)?"X":"";
			param["I_TRSTATUS"]	= status;
			param["I_REQUEST"] 	= bApproval ? "X":"";		// 'A' 승인요청/ 'S' 임시저장
			trace(param.toString());
			divideCurrencyTable3(table3);
			divideCurrencyTable4(table4);
			divideCurrencyTable5(table5);
			var tables:Object = new Object();
			tables["ITAB0"] = table0;
			tables["ITAB1"] = table1;
			tables["ITAB2"] = table2;
			tables["ITAB3"] = table3;
			tables["ITAB4"] = table4;
			tables["ITAB5"] = table5;
			
			saveData("Z_HR_T005", param, tables, resultSave, faultSave);
		}

		private function divideCurrencyTable3(table:Array):void
		{
			for each(var vo:* in table)
			{
				if(vo.WAERS == "KRW") {
					vo.WERT1 /= 100;
					vo.DAYPY /= 100;
				}
			}	
		}

		private function divideCurrencyTable4(table:Array):void
		{
			for each(var vo:* in table)
			{
				if(vo.WAERS == "KRW") {
					vo.PDRPY /= 100;
					vo.DAYPY /= 100;
					vo.UNITAMT /= 100;
				}
			}	
		}

		private function divideCurrencyTable5(table:Array):void
		{
			for each(var vo:* in table)
			{
				if(vo.WAERS == "KRW") {
					vo.AMT /= 100;
				}
			}	
		}

		/**
		 * data load를 수행
		 * 		- DataLoader 를 생성하고 Import Parameter 객체를 생성, RFC를 호출
		 * 
		 * @param pernr 사번,대상월
		 * @return void
		 */
		public function delBizTrip(status:String, key1:String, key2:String):void
		{
			var param:Object = new Object();
			param["I_GWAREKEY01"] = key1;
			param["I_GWAREKEY02"] = key2;
			
			loadData("Z_HR_T004", param, resultDelete, faultDelete);
		}
		
		
		
		///////////////////////////////////////////////////////////////////////////////////////////////////
		//
		//	Event Listeners
		//
		///////////////////////////////////////////////////////////////////////////////////////////////////
		/**
		 * 서버에서 정상적으로 리턴된 결과를 처리
		 * 
		 * @param
		 * @return void
		 */
		public function resultLoad(event:ResultEvent):void
		{
			if(retCode==0) { 
				summary = parsePlaceSummary(event.result.OTAB1);
				places = parsePlaceList(event.result.OTAB2);					// 출장지
				members = parseMemberList(event.result.OTAB3);					// 출장자
				adjustBase = parseAdjustBase(event.result.OTAB4);				// 정산기준
				memberAdjusts = parseMemberAdjustList(event.result.OTAB5);		// 출장자별 정산 요약
				memberCarfare = parseMemberCarfare(event.result.OTAB6);			// 출장자 별  일비 and 차량비용
				memberDetailCost = parseMemberDetailCost(event.result.OTAB7);	// 출장자별 세부 내용
				
				facade.sendNotification(BizTripFacade.LOAD_DOMESTIC_BIZTRIP_COMPLETE, this);
			}
			else {
				facade.sendNotification(BizTripFacade.LOAD_DOMESTIC_BIZTRIP_FAILED, this);
			}
		}
		
		/**
		 * 서버에서 오류가 발생했을 처리
		 * 
		 * @param
		 * @return void
		 */
		private function faultLoad(event:FaultEvent):void
		{
			facade.sendNotification(BizTripFacade.LOAD_DOMESTIC_BIZTRIP_FAILED, this);
		}
		
		
		/**
		 * 서버에서 정상적으로 리턴된 결과를 처리
		 * 
		 * @param
		 * @return void
		 */
		public function resultSave(event:ResultEvent):void
		{
			if(retCode==0) {  
				outKey = event.result["O_GWAREKEY"];
				trace("O_GWAREKEY: " + outKey);
				facade.sendNotification(BizTripFacade.SAVE_DOMESTIC_BIZTRIP_COMPLETE, this);
			}
			else {
				if(saveType == "A") {
					facade.sendNotification(BizTripFacade.APP_DOMESTIC_BIZTRIP_FAILED, this);
				}
				else {
					facade.sendNotification(BizTripFacade.SAVE_DOMESTIC_BIZTRIP_FAILED, this);
				}
			}
		}
		
		/**
		 * 서버에서 오류가 발생했을 처리
		 * 
		 * @param
		 * @return void
		 */
		private function faultSave(event:FaultEvent):void
		{
			if(saveType == "A") {
				facade.sendNotification(BizTripFacade.APP_DOMESTIC_BIZTRIP_FAILED, this);
			}
			else {
				facade.sendNotification(BizTripFacade.SAVE_DOMESTIC_BIZTRIP_FAILED, this);
			}
		}
		
		
		/**
		 * 서버에서 정상적으로 리턴된 결과를 처리
		 * 
		 * @param
		 * @return void
		 */
		public function resultDelete(event:ResultEvent):void
		{
			if(retCode==0) {  
				facade.sendNotification(BizTripFacade.DELETE_BIZTRIP_COMPLETE, this);
			}
			else {
				facade.sendNotification(BizTripFacade.DELETE_BIZTRIP_FAILED, this);
			}
		}
		
		/**
		 * 서버에서 오류가 발생했을 처리
		 * 
		 * @param
		 * @return void
		 */
		private function faultDelete(event:FaultEvent):void
		{
			facade.sendNotification(BizTripFacade.DELETE_BIZTRIP_FAILED, this);
			CursorManager.removeBusyCursor();
		}
		
		
		
		
		///////////////////////////////////////////////////////////////////////////////////////////////////
		//
		//	Data Parsing functions
		//
		///////////////////////////////////////////////////////////////////////////////////////////////////
		/**
		 * 서버에서 전달된 result 객체를 분석하여 Value Object를 생성
		 * 
		 * @param
		 * @return 제증명서 종류 Code list
		 */
		private function parsePlaceSummary(srcArr:ArrayCollection):BizTripSummaryVO
		{
			var summary:BizTripSummaryVO = new BizTripSummaryVO;
			if(srcArr.length>=1) {
				var rec:* = srcArr.getItemAt(0);
				summary.GWAREKEY01	= rec["GWAREKEY01"];
				summary.GWAREKEY02	= rec["GWAREKEY02"];
				summary.TRSTATUS	= rec["TRSTATUS"];
				summary.TRSTATX		= rec["TRSTATX"];
				summary.TRTYPE		= rec["TRTYPE"];
				summary.TTEXT		= rec["TTEXT"];
				summary.BEGDA		= DateUtil.stringToDateTime(rec["BEGDA"]);
				summary.ENDDA		= DateUtil.stringToDateTime(rec["ENDDA"]);
				summary.TRTITLE		= rec["TRTITLE"];
				summary.BTEXT		= rec["BTEXT"];
				summary.MNUM		= rec["MNUM"];
				summary.TRPAYC		= rec["TRPAYC"];
				summary.TRCONV		= rec["TRCONV"];
				summary.TRTEXT		= rec["TRTEXT"];
				summary.PURPOSE		= rec["PURPOSE"];
				summary.IPERNR		= StringUtil.trimFront(rec["IPERNR"], "0");
			}
			return summary;
		}

		/**
		 * 서버에서 전달된 result 객체를 분석하여 Value Object를 생성
		 * 
		 * @param
		 * @return 제증명서 종류 Code list
		 */
		private function parsePlaceList(srcArr:ArrayCollection):ArrayCollection
		{
			var list:ArrayCollection = new ArrayCollection;
			for each(var rec:Object in srcArr) 
			{
				var vo:BizTripPlaceVO = new BizTripPlaceVO();
				vo.SEQNO	= rec["SEQNO"];
				vo.BEGDA	= DateUtil.stringToDateTime(rec["BEGDA"]);
				vo.ENDDA	= DateUtil.stringToDateTime(rec["ENDDA"]);
				vo.LAND1	= rec["LAND1"];
				vo.LAGBN	= rec["LAGBN"];
				vo.BREN		= rec["BREN"];
				list.addItem(vo);
			}
			return list;
		}
		
		/**
		 * 서버에서 전달된 result 객체를 분석하여 Value Object를 생성
		 * 
		 * @param
		 * @return 제증명서 종류 Code list
		 */
		private function parseMemberList(srcArr:ArrayCollection):ArrayCollection
		{
			var list:ArrayCollection = new ArrayCollection;
			for each(var rec:Object in srcArr) 
			{
				var vo:BizTripMemberVO = new BizTripMemberVO();
				vo.PERNR	= StringUtil.trimFront(rec["PERNR"], "0");
				vo.ENAME	= rec["ENAME"];
				vo.ORGTX	= rec["ORGTX"];
				vo.JWTXT	= rec["JWTXT"];
				vo.BEGDA	= DateUtil.stringToDateTime(rec["BEGDA"]);
				vo.ENDDA	= DateUtil.stringToDateTime(rec["ENDDA"]);
				vo.WDAY		= rec["WDAY"];
				vo.BIGO		= rec["BIGO"];
				list.addItem(vo);
			}
			return list;
		}
		/**
		 * 서버에서 전달된 result 객체를 분석하여 Value Object를 생성
		 * 
		 * @param
		 * @return 제증명서 종류 Code list
		 */
		private function parseMemberAdjustList(srcArr:ArrayCollection):ArrayCollection
		{
			var list:ArrayCollection = new ArrayCollection;
			for each(var rec:Object in srcArr) 
			{
				var vo:MemberAdjustVO = new MemberAdjustVO();
				vo.PERNR	= StringUtil.trimFront(rec["PERNR"], "0");
				vo.ENAME	= rec["ENAME"];
				vo.TRTICH	= rec["TRTICH"];		// 일비지급여부
				vo.RCARC	= rec["RCARC"];			// 숙박제공여부
				vo.DAYPY	= rec["DAYPY"];			// 일비
				vo.PCARC	= rec["PCARC"];			// 개인차량이용
				vo.OCARC	= rec["OCARC"];			// 회사차량이용
				vo.PCAPY	= rec["PCAPY"];			// 유류비
				vo.EATPY	= rec["EATPY"];			// 식비
				vo.STYPY	= rec["STYPY"];			// 숙박비
				vo.TRAPY	= rec["TRAPY"];			// 교통비
				vo.AIRPY	= rec["AIRPY"];			// 항공료
				vo.WAERS	= rec["WAERS"];			// 통화 키
				if(vo.WAERS == "KRW") {
					vo.DAYPY = Math.round(vo.DAYPY*100);
					vo.PCAPY = Math.round(vo.PCAPY*100);
					vo.EATPY = Math.round(vo.EATPY*100);
					vo.STYPY = Math.round(vo.STYPY*100);
					vo.TRAPY = Math.round(vo.TRAPY*100);
					vo.AIRPY = Math.round(vo.AIRPY*100);
				}
				list.addItem(vo);
			}
			return list;
		}

		private function parseMemberCarfare(srcArr:ArrayCollection):ArrayCollection
		{
			var list:ArrayCollection = new ArrayCollection;
			for each(var rec:Object in srcArr) 
			{
				var vo:MemberCarfareVO = new MemberCarfareVO();
				vo.PERNR	= StringUtil.trimFront(rec["PERNR"], "0");
				vo.TRTICH	= rec["TRTICH"];		// 일비 제공여부
				vo.DAYPY 	= rec["DAYPY"]; 
				vo.RCARC	= rec["RCARC"];			// 숙식제공여부
				vo.PCARC	= rec["PCARC"];			// 개인차량이용
				vo.OCARC	= rec["OCARC"];			// 회사차량이용
				vo.DRIKM	= rec["DRIKM"];			// 거리
				vo.UNITAMT	= rec["UNITAMT"];		// 단가. 
				vo.PDRPY	= rec["PDRPY"];			// 유류비
				vo.WAERS	= rec["WAERS"];			// 
				if(vo.WAERS == "KRW") {
					vo.DAYPY = Math.round(vo.DAYPY*100);
					vo.PDRPY = Math.round(vo.PDRPY*100);
					vo.UNITAMT = Math.round(vo.UNITAMT*100);
				}
				list.addItem(vo);
			}
			return list;
		}
		
		private function parseMemberDetailCost(srcArr:ArrayCollection):ArrayCollection
		{
			var list:ArrayCollection = new ArrayCollection;
			for each(var rec:Object in srcArr) 
			{
				var vo:MemberDetailCostVO = new MemberDetailCostVO();
				vo.PERNR	= StringUtil.trimFront(rec["PERNR"], "0");
				vo.SEQNO	= rec["SEQNO"];
				vo.CARDNO	= rec["CARDNO"];		// 카드번호
				vo.APNO		= rec["APNO"];			// 승인번호
				vo.RECGBN	= rec["RECGBN"];		// 증빙구분
				vo.RECTXT	= rec["RECTXT"];		//  
				vo.RDATE	= DateUtil.stringToDateTime(rec["RDATE"]);			// 증빙일자
				vo.MERNM	= rec["MERNM"];			// 가맹정명
				vo.AMT		= rec["AMT"];			// 금액
				vo.WAERS	= rec["WAERS"];			// 통화 키
				vo.COSTGBN	= rec["COSTGBN"];		// 비용구분
				vo.COSTEXT	= rec["COSTEXT"];		//  
				vo.BIGO		= rec["BIGO"];			// 비고
				vo.RBELNR	= rec["RBELNR"];		// 회계 전표 번호
				vo.RBTEXT	= rec["RBTEXT"];		// 전표오류메세지
				if(vo.WAERS == "KRW") {
					vo.AMT = Math.round(vo.AMT*100);
				}
				list.addItem(vo);
				/*
				if(vo.COSTGBN == "05") {
					var memberAdjust:MemberAdjustVO = getMemberAdjust(vo.PERNR);
					if(memberAdjust!=null) {
						//memberAdjust.PCAPY += vo.AMT;
					}
				}
				*/
			}
			return list;
		}
		/**
		 * 서버에서 전달된 result 객체를 분석하여 Value Object를 생성
		 * 
		 * @param
		 * @return 제증명서 종류 Code list
		 */
		private function parseAdjustBase(srcArr:ArrayCollection):ArrayCollection
		{
			var list:ArrayCollection = new ArrayCollection;
			for each(var rec:Object in srcArr) 
			{
				var vo:AdjustBaseVO = new AdjustBaseVO();
				vo.KOSTL	= rec["KOSTL"];
				vo.WERT1	= rec["WERT1"];
				vo.KDATE	= DateUtil.stringToDateTime(rec["KDATE"]);
				//trace("load KDATE = " + vo.KDATE + ", " + rec["KDATE"]);
				vo.KURSF01	= rec["KURSF01"];
				vo.KURSF02	= rec["KURSF02"];
				vo.DAYPY	= rec["DAYPY"];
				vo.WAERS	= rec["WAERS"];
				if(vo.WAERS == "KRW") {		// 
					vo.WERT1 = Math.round(vo.WERT1*100)
					vo.DAYPY = Math.round(vo.DAYPY*100)
				}
				vo.TRSTATUS	= rec["TRSTATUS"];
				vo.TRSTATX  = rec["TRSTATX"];
				vo.TRTEXT	= rec["TRTEXT"];
				list.addItem(vo);
			}
			return list;
		}
		
		private function getMemberAdjust(pernr:String):MemberAdjustVO
		{
			for each(var vo:MemberAdjustVO in memberAdjusts) {
				if(pernr == vo.PERNR) return vo; 
			}
			return null;
		}
	}
}